import logging
import glob
import os

import yagmail
from config.config import smtp_cfg


# 发送邮件
class Email_Utils:
    def __init__(self):
        self.user = smtp_cfg['user']
        self.password = smtp_cfg['password']
        self.host = smtp_cfg['host']

    def send_email(self, log_file_name):
        email = yagmail.SMTP(user=self.user, password=self.password, host=self.host)
        attachments = glob.glob(log_file_name) + glob.glob('./zipfile/*.zip')
        email.send(to=self.user, subject='互帮互助管理系统项目测试报告', contents='本次生成的测试报告是关于互帮互助管理系统项目项目的接口自动化测试', attachments=attachments)
        email.close()

# utils/email_util.py
# import yagmail
# from config.config import smtp_cfg
# import os
# import logging
#
# class Email_Utils:
#     def __init__(self):
#         self.user = smtp_cfg['user']
#         self.password = smtp_cfg['password']
#         self.host = smtp_cfg['host']
#         self.logger = logging.getLogger(__name__)
#
#     def send_email(self, attachments=None, recipients=None, subject='测试报告'):
#         """发送带附件的邮件，支持多个附件"""
#         # 处理收件人
#         recipients = recipients or [self.user]
#
#         # 处理附件（确保是列表）
#         if not attachments:
#             attachments = []
#         elif not isinstance(attachments, list):
#             attachments = [attachments]
#
#         # 验证每个附件是否存在
#         valid_attachments = []
#         for file_path in attachments:
#             if isinstance(file_path, str):
#                 # 规范化路径（处理空格和特殊字符）
#                 file_path = os.path.normpath(file_path)
#                 if os.path.exists(file_path):
#                     valid_attachments.append(file_path)
#                     self.logger.info(f"添加有效附件: {file_path}")
#                 else:
#                     self.logger.warning(f"附件不存在: {file_path}")
#             else:
#                 self.logger.warning(f"附件类型不支持: {type(file_path)}")
#
#         # 如果没有有效附件，是否继续发送？
#         if not valid_attachments:
#             self.logger.warning("没有有效附件，邮件将不包含附件")
#
#         # 发送邮件
#         try:
#             with yagmail.SMTP(user=self.user, password=self.password, host=self.host) as yag:
#                 yag.send(
#                     to=recipients,
#                     subject=subject,
#                     contents='本次测试执行的详细报告及日志，请查收。',
#                     attachments=valid_attachments
#                 )
#             self.logger.info(f"邮件发送成功，收件人: {', '.join(recipients)}")
#         except Exception as e:
#             self.logger.error(f"邮件发送失败: {str(e)}", exc_info=True)
#             raise
